from . import admin
from flask import jsonify,request,session
import simplejson as json
import os,sys
import pandas as pd
from pandasql import sqldf
sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],"../../tools/"))
sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],"../../tools/db2tools/"))
from Db2Base import Db2Base
from Db2Connection import Db2Connection
import Tools


@admin.route("/test/<palette>/", methods=["GET", "POST"])
def hello_world(palette):
    """测试使用
    用来测试
    ---
    parameters:
      - name: palette
        in: path
        type: string
        enum: ['all', 'rgb', 'cmyk']
        required: true
        default: all
    definitions:
      Palette:
        type: object
        properties:
          palette_name:
            type: array
            items:
              $ref: '#/definitions/Color'
      Color:
        type: string
    responses:
      200:
        description: 返回颜色的类型
        schema:
          $ref: '#/definitions/Palette'
        examples:
          rgb: ['red', 'green', 'blue']
    """


    all_colors = {
        'cmyk': ['cian', 'magenta', 'yellow', 'black'],
        'rgb': ['red', 'green', 'blue']
    }
    if palette == 'all':
        result = all_colors
    else:
        result = {palette: all_colors.get(palette)}

    return jsonify(result)

@admin.route("/login", methods=["POST"])
def login():
    """登录
    用户登录
    ---
    parameters:
      - name: params
        in: body
        description: Updated name of the pet
        required: false
        type: string
    responses:
      200:
        description: 返回session_id
    """
    data = json.loads(request.get_data().decode('utf-8'))
    print(data)
    result={}
    result["rtn_code"] = "0000"
    result["rtn_desc"] = "OK"
    sysUserDao = Db2Base("lego","sys_user",Db2Connection.getEngine())
    t={}
    t["loginname"] = data["username"]
    t["passwd"] = data["password"]
    sys_user_list = sysUserDao.getT(t)
    if len(sys_user_list)==0:
        result["rtn_code"] = 404
        result["rtn_desc"] = "用户名或密码不正确"

    else:
        data={}
        data["token"] = Tools.generate_token("chenc")
        data["loginname"] = sys_user_list[0]["loginname"]
        data["username"] = sys_user_list[0]["username"]

        result["rtn_code"] = 200
        result["rtn_desc"] = "用户名验证成功"
        result["data"] = data

        '''获得用户的角色'''
        sysUserRoleDao = Db2Base("lego","SYS_USER_ROLE", Db2Connection.getEngine())
        t={}
        t["userid"] = sys_user_list[0]["userid"]
        sysUserRoleDaoList = sysUserRoleDao.getT(t)
        roleList = []
        for v in sysUserRoleDaoList:
            roleList.append(v["roleid"])
        data["roles"] = roleList
        session[data["token"]] = data

    return jsonify(result)

@admin.route("/logout", methods=["post"])
def logout():
    """登出
    销毁用户登录信息
    ---
    parameters:
      - name: params
        in: body
        description: Updated name of the pet
        required: false
        type: string
    responses:
      200:
        description: 返回session_id
    """
    data = json.loads(request.get_data().decode('utf-8'))
    token = data.get("token")
    print("token:"+token)
    result ={}
    if token in session:
        result["rtn_code"] = 200
        result["rtn_desc"] = "拉取客户信息成功"
        session.pop(token, None)
    else:
        result["rtn_code"] = 50008
        result["rtn_desc"] = "token不存在"
    return jsonify(result)

@admin.route("/user/info", methods=["get"])
def getUserInfo():
    """获取用户信息
    获取用户信息以及菜单信息
    ---
    parameters:
      - name: params
        in: body
        description: Updated name of the pet
        required: false
        type: string
    responses:
      200:
        description: 返回session_id
    """
    token = request.args.get('token')
    print("token:"+token)
    result ={}
    if token in session:
        result["rtn_code"] = 200
        result["rtn_desc"] = "拉取客户信息成功"
        result["user_info"] = session[token]

        '''获得用户对应的权限菜单'''
        roleListStr = str(result["user_info"]["roles"])
        roleListStr = roleListStr.replace("[", "")
        roleListStr = roleListStr.replace("]", "")

        sysRoleMenuRightDao = Db2Base("lego","SYS_ROLE_MENU_RIGHT", Db2Connection.getEngine())
        res = sysRoleMenuRightDao.getTByCondition("roleid in (%s)"%roleListStr)
        menuList=[]
        for v in res:
            menuList.append(v["menuid"])
        menuList = list(set(menuList))

        menuListStr = str(menuList)
        menuListStr = menuListStr.replace("[", "")
        menuListStr = menuListStr.replace("]", "")

        sql = "select menuid,upperid,menuname,iconcls from sys_menu"
        df = pd.read_sql(sql, Db2Connection.getNewConnection())
        df_menuid = sqldf("select * from df where menuid in (%s)"%menuListStr)
        df_upperid = sqldf("select distinct(upperid) from df_menuid")
        upperid_list = df_upperid.to_dict("record")

        menu_list = []
        for v in upperid_list:
            upperid = v["upperid"]
            print(upperid)
            df_upperid_detail = sqldf("select * from df where menuid ='%s'"%upperid)
            upperid_detail = df_upperid_detail.loc[0]
            t={}
            t["path"] = upperid_detail["menuid"]
            t["name"] = upperid_detail["menuid"]
            t["title"] = upperid_detail["menuname"]
            t["icon"] = upperid_detail["iconcls"]
            t["component"] = "layout/Layout"
            sub_menu=[]
            sub_menu_df = sqldf("select * from df_menuid where upperid ='%s'"%upperid)
            sub_menu_list = sub_menu_df.to_dict("record")
            for a in sub_menu_list:
                b = {}
                b["component"] = a["upperid"]+'/'+a["menuid"]
                b["path"] = a["menuid"]
                b["name"] = a["menuid"]
                b["title"] = a["menuname"]
                b["icon"] = a["iconcls"]
                sub_menu.append(b)
            t["sub_menu"] = sub_menu
            menu_list.append(t)

        result["menu_list"] = menu_list

    else:
        result["rtn_code"] = 50008
        result["rtn_desc"] = "token不存在"

    return jsonify(result)

@admin.route("/user/menu", methods=["get"])
def getUserMenu():
    """获取用户菜单
    获取用户信息以及菜单信息
    ---
    parameters:
      - name: params
        in: body
        description: Updated name of the pet
        required: false
        type: string
    responses:
      200:
        description: 返回session_id
    """
    token = request.args.get('token')
    print("token:"+token)
    result ={}
    if token in session:
        result["rtn_code"] = 200
        result["rtn_desc"] = "拉取客户信息成功"
        result["user_info"] = session[token]
    else:
        result["rtn_code"] = 50008
        result["rtn_desc"] = "token不存在"

    return jsonify(result)
